//
//  RHDeviceElectricEnergyVC.m
//  RuiHeAppApp
//
//  Created by Yan Chen on 2024/4/18.
//

#import "RHDeviceElectricEnergyVC.h"
#import "RHDeviceElectricCell.h"
#import "RHEnergyStatisticsCell.h"
#import "DevChartParamsModel.h"
#import "DeviceChartFieldModel.h"
#import "DevChartModel.h"
#import "SYChartTool.h"
#import "WSDatePickerView.h"
#import "RHDevicePowerFullChartVC.h"
#import "RHDevEndPointDataModel.h"
@interface RHDeviceElectricEnergyVC ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic ,strong) UITableView *tableView;

@property (nonatomic ,strong) NSArray *dataArr;

@property (nonatomic ,strong) DevChartParamsModel *chartParamsModel;

@property (nonatomic ,strong) RHDevEndPointDataModel *emuModel;

@property (nonatomic ,strong) NSDictionary *electricDataDic;
@end

@implementation RHDeviceElectricEnergyVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self createData];
    [self setupUI];
    [self getData];
}

- (void)setupUI{
    kWeakSelf;
    
    self.electricDataDic = @{
        @"load":@"-- (kWh)",
        @"solar":@"-- (kWh)",
        @"chg":@"-- (kWh)",
        @"dchg":@"-- (kWh)",
        @"buy":@"-- (kWh)",
        @"sell":@"-- (kWh)"
    };
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    _tableView.backgroundColor = CFTabViewBgColor;
    [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [_tableView setDelegate:self];
    [_tableView setDataSource:self];
    [_tableView registerClass:[RHDeviceElectricCell class] forCellReuseIdentifier:@"RHDeviceElectricCell"];
    [_tableView registerClass:[RHEnergyStatisticsCell class] forCellReuseIdentifier:@"PEElectricStatisticsCell"];
    [self.view addSubview:_tableView];
    
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsMake(0, 0, 0, 0));
    }];
    
    [_tableView addHeaderRefresh:^{
        [weakSelf getData];
        if (weakSelf.updateDevInfoBlock) {
            weakSelf.updateDevInfoBlock();
        }
    }];
}

-(void)createData
{
    NSDictionary *dict = [SYChartTool readLocalJsonFileWithName:@"DeviceElectric"];
    self.chartParamsModel = [DevChartParamsModel yy_modelWithDictionary:dict];
    self.chartParamsModel.maxSelectCount = 7;
}

//获取端点关系
-(void)getDevRelation
{
    [RHDevEndPointDataModel startGetWithCompletionAPIKey:H_getDevRelation argument:@{@"deviceId":self.devModel.deviceId} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
            if(resultModel.code == 200){
                if(ValidDict(request.responseJSONObject[@"data"])){
                    NSArray *arr = [NSArray yy_modelArrayWithClass:[RHDevEndPointDataModel class] json:request.responseJSONObject[@"data"][@"data"]];
                    //筛选出EMU
                   
                    [arr enumerateObjectsUsingBlock:^(RHDevEndPointDataModel  *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                            if([obj.type isEqualToString:@"EMU"]){
                                self.emuModel = obj;
                                *stop = YES;
                            }
                    }];
                    
                    if (self.emuModel) {
                        [self getData];
                    }else{
                        [self getRegularStatisticsWithChartModel:[self.chartParamsModel.chartList firstObject]];
                    }
                }
            }
            [self.tableView endHeaderRefresh];
        } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
            [self.tableView endHeaderRefresh];
    }];
}

-(void)getData
{
    if(self.emuModel == nil){
        [self getDevRelation];
    }else{
        [self getFormData];
        [self getRegularStatisticsWithChartModel:[self.chartParamsModel.chartList firstObject]];
    }
}


#pragma mark ------ 电能统计

-(void)getRegularStatisticsWithChartModel:(DevChartModel*)chartModel
{
    NSString *type = @"day";
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:[chartModel.curTime integerValue]];
    NSInteger currentTime = [date timeIntervalSince1970]*1000;
    
    NSTimeZone *zone  = [NSTimeZone systemTimeZone];
    if(chartModel.timeType == TimeType_Day){
        type = @"day";
    }else if (chartModel.timeType == TimeType_Month){
        type = @"month";
    }else if (chartModel.timeType == TimeType_Year){
        type = @"year";
    }
    [QMUITips showLoadingInView:self.view];
    NSDictionary *para = @{@"deviceId":self.devModel.deviceId,@"currentTime":@(currentTime),@"dateRange":type,@"timeZone":zone.name};
    [BaseModel startWithCompletionAPIKey:H_getRegularStatistics argument:para
    requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.tableView endHeaderRefresh];
        chartModel.allDataArray = request.responseJSONObject[@"data"];
        [self.tableView reloadData];
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.tableView endHeaderRefresh];
        
    }];
}




//底部数据(电能数据(累计))
- (void)getFormData{
    DevChartModel *chartModel = [self.chartParamsModel.chartList firstObject];
    NSMutableArray *paraKey = [NSMutableArray array];
    for (DeviceChartFieldModel *fileld in self.chartParamsModel.formFields) {
        [paraKey addObject:fileld.keyCode];
    }
    
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:[chartModel.curTime integerValue]];
    NSDate *begin_date = [NSDate dateWithYear:date.year month:date.month day:date.day hour:0 minute:0 second:0];
    NSDate *end_date = [NSDate dateWithYear:date.year month:date.month day:date.day hour:23 minute:59 second:59];
    
    if (chartModel.timeType == TimeType_Month) {
        //这个月有多少天
        NSInteger dayOfMonth = [date monthDayWithYear:date.year month:date.month];
        begin_date = [NSDate dateWithYear:date.year month:1 day:1 hour:0 minute:0 second:0];
        end_date = [NSDate dateWithYear:date.year month:date.month day:dayOfMonth hour:23 minute:59 second:59];
    }
    if (chartModel.timeType == TimeType_Year) {
        //这个月有多少天
        NSInteger dayOfMonth = [date monthDayWithYear:date.year month:12];
        begin_date = [NSDate dateWithYear:date.year month:1 day:1 hour:0 minute:0 second:0];
        end_date = [NSDate dateWithYear:date.year month:12 day:dayOfMonth hour:23 minute:59 second:59];
    }
    
    NSString *begin_time = [NSString stringWithFormat:@"%zd",(NSInteger)[begin_date timeIntervalSince1970]*1000];
    NSString *end_time = [NSString stringWithFormat:@"%zd",(NSInteger)[end_date timeIntervalSince1970]*1000];
    
    NSArray *keys = @[@"Emu_LE_Day",@"Emu_BCE_Day",@"Emu_BDE_Day",@"Emu_GGE_Day",@"Emu_GPE_Day",@"Emu_PPG_Day"];
    if (chartModel.timeType == TimeType_Month) {
        keys = @[@"Emu_LE_Mon",@"Emu_BCE_Mon",@"Emu_BDE_Mon",@"Emu_GGE_Mon",@"Emu_GPE_Mon",@"Emu_PPG_Mon"];
    }
    if (chartModel.timeType == TimeType_Year) {
        keys = @[@"Emu_LE_Year",@"Emu_BCE_Year",@"Emu_BDE_Year",@"Emu_GGE_Year",@"Emu_GPE_Year",@"Emu_PPG_Year"];
    }
    NSDictionary *para = @{@"deviceId":self.devModel.deviceId,
                           @"startTime":begin_time,
                           @"endTime":end_time
    };
     //D_getLastEndpointData
    [BaseModel startGetWithCompletionAPIKey:H_getDeviceElectricEnergyInfo argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.tableView endHeaderRefresh];
        if(resultModel.code == 200){
            if([request.responseObject[@"data"] isKindOfClass:[NSDictionary class]]){
                NSDictionary *dic = request.responseObject[@"data"];
                
                NSString* load  = [NSDecimalNumber decimalStringWithDoubleString:dic[@"load"] nullStr:@"--"];
                NSString* chg   = [NSDecimalNumber decimalStringWithDoubleString:dic[@"batteryCharge"] nullStr:@"--"];
                NSString* dchg  = [NSDecimalNumber decimalStringWithDoubleString:dic[@"batteryDischarge"] nullStr:@"--"];
                NSString* buy   = [NSDecimalNumber decimalStringWithDoubleString:dic[@"gridCharge"] nullStr:@"--"];
                NSString* sell  = [NSDecimalNumber decimalStringWithDoubleString:dic[@"gridDischarge"] nullStr:@"--"];
                NSString* solar = [NSDecimalNumber decimalStringWithDoubleString:dic[@"pv"] nullStr:@"--"];
//                if (chartModel.timeType == TimeType_Month) {
//                    load  = [NSDecimalNumber decimalStringWithDoubleString:dic[@"Emu_LE_Mon"] nullStr:@"--"];
//                    chg   = [NSDecimalNumber decimalStringWithDoubleString:dic[@"Emu_BCE_Mon"] nullStr:@"--"];
//                    dchg  = [NSDecimalNumber decimalStringWithDoubleString:dic[@"Emu_BDE_Mon"] nullStr:@"--"];
//                    buy   = [NSDecimalNumber decimalStringWithDoubleString:dic[@"Emu_GGE_Mon"] nullStr:@"--"];
//                    sell  = [NSDecimalNumber decimalStringWithDoubleString:dic[@"Emu_GPE_Mon"] nullStr:@"--"];
//                    solar = [NSDecimalNumber decimalStringWithDoubleString:dic[@"Emu_PPG_Mon"] nullStr:@"--"];
//                }
//                if (chartModel.timeType == TimeType_Year) {
//                    load  = [NSDecimalNumber decimalStringWithDoubleString:dic[@"Emu_LE_Year"] nullStr:@"--"];
//                    chg   = [NSDecimalNumber decimalStringWithDoubleString:dic[@"Emu_BCE_Year"] nullStr:@"--"];
//                    dchg  = [NSDecimalNumber decimalStringWithDoubleString:dic[@"Emu_BDE_Year"] nullStr:@"--"];
//                    buy   = [NSDecimalNumber decimalStringWithDoubleString:dic[@"Emu_GGE_Year"] nullStr:@"--"];
//                    sell  = [NSDecimalNumber decimalStringWithDoubleString:dic[@"Emu_GPE_Year"] nullStr:@"--"];
//                    solar = [NSDecimalNumber decimalStringWithDoubleString:dic[@"Emu_PPG_Year"] nullStr:@"--"];
//                }
                
                
                
                self.electricDataDic = @{
                    @"load":load,
                    @"solar":solar,
                    @"chg":chg,
                    @"dchg":dchg,
                    @"buy":buy,
                    @"sell":sell
                };
                [self.tableView reloadData];
            }
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.tableView endHeaderRefresh];
    }];
}


#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 1;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    UIView *headView = kView;
    headView.backgroundColor = CFTabViewBgColor;
    UILabel *titleLab = [[QMUILabel alloc]init];
    titleLab.font = kBOLDSYSTEMFONT(16);
    titleLab.textColor = kColorRGB(0, 0, 0);
    titleLab.textAlignment = NSTextAlignmentLeft;
    titleLab.text = @"电能数据".rh_localized;
    [headView addSubview:titleLab];
    
    [titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(headView).offset(15);
        make.bottom.mas_offset(-10);
     }];
    if(section ==0){
        titleLab.hidden = YES;
    };
   return nil;
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if(section == 0)return 15;
    return 15;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.0;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return nil;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    kWeakSelf;
    if(indexPath.section == 1){
        //电能曲线
        RHEnergyStatisticsCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PEElectricStatisticsCell"];
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        DevChartModel *chartModel = [self.chartParamsModel.chartList firstObject];
        [cell setChartModel:chartModel];
       
        cell.chartModel = chartModel;
         //选择参数
         cell.selectTopToolBlock = ^(NSInteger index) {
             [weakSelf selectTopTool:index atIndexpath:indexPath];
         };
         
         cell.subTimeBlock = ^{//日期往前
             [weakSelf subTimeAction:indexPath];
         };
         
         cell.addTimeBlock = ^{//日期往后
             [weakSelf addTimeAction:indexPath];
         };
         
         cell.changeTimeBlock = ^{//选择日期
             [weakSelf changeDate:indexPath];
         };
         
         //全屏
        kWeakSelf;
        cell.fullChartBlock = ^{
            DevChartModel *chartModel = [weakSelf.chartParamsModel.chartList lastObject];
            DevChartModel *fullModel = [chartModel modelCopy];
            RHDevicePowerFullChartVC *vc = [[RHDevicePowerFullChartVC alloc] initWithModel:fullModel deviceModel:weakSelf.devModel toolType:0];
            vc.lineChartType = @"electric";
            [weakSelf.navigationController pushViewController:vc animated:NO];
        };
        cell.contentView.backgroundColor = CFTabViewBgColor;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    //功率数据  电能数据
    RHDeviceElectricCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RHDeviceElectricCell"];
    cell.dic = self.electricDataDic;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
   
}

#pragma mark ----------------- Action --------------------
#pragma mark ----- 参数 , 年 , 月 , 日选项 -------------
//工具选择项
- (void)selectTopTool:(NSInteger)index atIndexpath:(NSIndexPath *)indexpath{
    
    DevChartModel *chartModel = [self.chartParamsModel.chartList firstObject];
    
    
    if (index == 0) {//Day
        chartModel.timeType = TimeType_Day;
        NSDate *date = [NSDate date];
        NSTimeInterval interval = [date timeIntervalSince1970];
        chartModel.curTime = [NSString stringWithFormat:@"%d",(int)interval];
        chartModel.params = chartModel.dayParams;
        [self.tableView reloadData];
       
    }else if (index == 1) {//Month
        chartModel.timeType = TimeType_Month;
        NSDate *date = [NSDate date];
        NSTimeInterval interval = [date timeIntervalSince1970];
        chartModel.curTime = [NSString stringWithFormat:@"%d",(int)interval];
        chartModel.params = chartModel.monthParams;
        chartModel.allDataArray = @[];
        [self.tableView reloadData];
        
    }else if (index == 2) {//Year
        chartModel.timeType = TimeType_Year;
        NSDate *date = [NSDate date];
        NSTimeInterval interval = [date timeIntervalSince1970];
        chartModel.curTime = [NSString stringWithFormat:@"%d",(int)interval];
        chartModel.params = chartModel.yearParams;
        chartModel.allDataArray = @[];
        [self.tableView reloadData];
        
    }else if (index == 4) {//Total
        chartModel.timeType = TimeType_Total;
       
    }
    
    [self getData];

}
#pragma mark ------ 选择日期 ------
//变更日期
- (void)changeDate:(NSIndexPath *)indexpath{
    DevChartModel *chartModel;
 
    chartModel = [self.chartParamsModel.chartList firstObject];
   
    WSDateStyle dataStyle = DateStyleShowYearMonthDay;
    if (chartModel.timeType == TimeType_Day) {
        dataStyle = DateStyleShowYearMonthDay;
    }else if (chartModel.timeType == TimeType_Month){
        dataStyle = DateStyleShowYearMonth;
    }else if (chartModel.timeType == TimeType_Year){
        dataStyle = DateStyleShowYear;
    }

    @weakify(self);
    WSDatePickerView *datePickerV = [[WSDatePickerView alloc] initWithDateStyle:dataStyle CompleteBlock:^(NSDate *selectDate) {
        @strongify(self);
        //NSString *currentDate = [selectDate stringWithFormat: dateFormatStr];//年-月-日-时-分
        NSUInteger timeSp = [selectDate timeIntervalSince1970];
        chartModel.curTime = [NSString stringWithFormat:@"%d",(int)timeSp];
        
       
        [self getData];
       
    }];
    datePickerV.dateLabelColor = FontColor(@"#3ECE80");//年-月 颜色
    datePickerV.datePickerColor = UIColorBlack;//滚轮日期颜色
    datePickerV.doneButtonColor = UIColor.blackColor;//确定按钮的颜色
    if (chartModel.timeType == TimeType_Day) {
        datePickerV.maxLimitDate = [NSDate date];
        datePickerV.minLimitDate = [NSDate dateWithYear:[NSDate date].year-5 month:[NSDate date].month day:[NSDate date].day hour:[NSDate date].hour minute:[NSDate date].minute second:[NSDate date].second];
    }else if (chartModel.timeType == TimeType_Month){

    }else if (chartModel.timeType == TimeType_Year){
        datePickerV.maxLimitDate = [NSDate date];
        datePickerV.minLimitDate = [NSDate dateWithYear:[NSDate date].year-5 month:[NSDate date].month day:[NSDate date].day hour:[NSDate date].hour minute:[NSDate date].minute second:[NSDate date].second];
    }
    [datePickerV show];
}
#pragma mark ------ 后一天 -------
//日期累加
- (void)addTimeAction:(NSIndexPath *)indexpath{
    DevChartModel *chartModel;
    
    chartModel = [self.chartParamsModel.chartList firstObject];
  
    if (chartModel.timeType == TimeType_Total) {
        return;
    }
    
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:[chartModel.curTime integerValue]];
    NSDate *nextDate;
    if (chartModel.timeType == TimeType_Day) {
        nextDate = [date dateByAddingDays:1];
    }else if (chartModel.timeType == TimeType_Month){
        nextDate = [date dateByAddingMonths:1];
    }else if (chartModel.timeType == TimeType_Year){
        nextDate = [date dateByAddingYears:1];
    }
    NSTimeInterval interval = [nextDate timeIntervalSince1970];
    chartModel.curTime = [NSString stringWithFormat:@"%ld",(long)interval];
    
    
   
    [self getData];
    
}

#pragma mark ------ 前一天 -------
//日期累减
- (void)subTimeAction:(NSIndexPath *)indexpath{
    DevChartModel *chartModel;
  
    chartModel = [self.chartParamsModel.chartList firstObject];
   
    
    if (chartModel.timeType == TimeType_Total) {
        return;
    }
    
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:[chartModel.curTime integerValue]];
    NSDate *nextDate;
    if (chartModel.timeType == TimeType_Day) {
        nextDate = [date dateBySubtractingDays:1];
    }else if (chartModel.timeType == TimeType_Month){
        nextDate = [date dateBySubtractingMonths:1];
    }else if (chartModel.timeType == TimeType_Year){
        nextDate = [date dateBySubtractingYears:1];
    }
    NSTimeInterval interval = [nextDate timeIntervalSince1970];
    chartModel.curTime = [NSString stringWithFormat:@"%d",(int)interval];
    
    
    [self getData];
   
}






-(UIView *)listView
{
    return self.view;
}



@end
